package com.example.demo.interceptor;

import com.alibaba.fastjson.JSONObject;

import com.example.demo.result.Result;
import com.example.demo.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override//目标资源方法运行前运行返回tu're放行  返回false不放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 强制转换请求和响应对象为HttpServletRequest和HttpServletResponse
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        // 获取请求的URL
        String url = req.getRequestURL().toString();
        // 记录拦截的请求
        log.info("拦截请求:{}", url);

        // 如果是登录请求，直接放行
        if (url.contains("login")) {
            log.info("登录请求,放行");
//            filterChain.doFilter(req, resp);

            return true;
        }

        // 从请求头中获取JWT令牌
        String jwt = req.getHeader("token");

        // 如果没有携带JWT令牌，返回未登录错误
        if (!StringUtils.hasLength(jwt)) {
            log.info("未携带token,拦截");
            Result error = Result.error("NOT_LOGIN");
            // 将错误结果转换为JSON字符串
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return false;
        }

        // 尝试解析JWT令牌，如果解析失败，返回未登录错误
        try {
            JwtUtils.parseJWT(jwt); // 解析jwt
        } catch (Exception e) {
            log.info("解析jwt失败");
            Result error = Result.error("NOT_LOGIN");
            // 将错误结果转换为JSON字符串
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return false;
        }

        // 如果JWT合法，放行请求
        log.info("jwt合法,放行");
//        filterChain.doFilter(servletRequest, servletResponse);
        return true;
    }

    @Override//目标资源方法运行后运行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override//请求处理完成之后运行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
